from django.http import JsonResponse
from web.models import ClockIn, ClockInPhoto, Users
from django.views.decorators.csrf import csrf_exempt
from django.forms import model_to_dict
from django import forms
from web.apis import tools


# 打卡表单
class ClockInForm(forms.ModelForm):
    class Meta:
        model = ClockIn
        fields = ['user', 'clock_type', 'clock_location', 'remark']


# 打卡照片表单
class ClockInPhotoForm(forms.ModelForm):
    class Meta:
        model = ClockInPhoto
        fields = ['clock_in', 'photo']


# 打卡API
@csrf_exempt
def create_clock_in(request):
    if request.method == 'POST':
        form = ClockInForm(request.POST)
        if form.is_valid():
            form.save()
            return JsonResponse(tools.ReturnData(code=200, msg='打卡成功',data=form.instance.id))
        else:
            error_msg = tools.get_first_error(form)
            return JsonResponse(tools.ReturnData(code=400, msg=f'打卡失败: {error_msg}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))


# 上传打卡图片
@csrf_exempt
def upload_clock_in_photo(request):
    if request.method == 'POST':
        form = ClockInPhotoForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return JsonResponse(tools.ReturnData(code=200, msg='上传打卡图片成功'))
        else:
            error_msg = tools.get_first_error(form)
            return JsonResponse(tools.ReturnData(code=400, msg=f'上传打卡图片失败: {error_msg}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))


# 获取打卡列表
@csrf_exempt
def get_clock_in_list(request):
    if request.method == 'GET':
        clock_ins = ClockIn.objects.all().order_by('-clock_time')
        data = []
        for clock_in in clock_ins:
            user = clock_in.user
            user_dict = model_to_dict(user)
            user_dict['avatar'] = user.avatar.url if user.avatar else None
            del user_dict['password']
            clock_in_dict = model_to_dict(clock_in)
            clock_in_dict['clock_time'] = clock_in.clock_time.strftime('%Y-%m-%d %H:%M:%S')
            clock_in_dict['clock_type'] = clock_in.get_clock_type_display()
            clock_in_dict['user'] = user_dict

            # 获取打卡照片
            photos = ClockInPhoto.objects.filter(clock_in=clock_in)
            photos_data = []
            for photo in photos:
                photo_dict = model_to_dict(photo)
                photo_dict['photo'] = photo.photo.url
                photos_data.append(photo_dict)
            clock_in_dict['photos'] = photos_data
            
            data.append(clock_in_dict)
        return JsonResponse(tools.ReturnData(code=200, data=data))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))


# 获取当前用户的打卡记录
@csrf_exempt
def get_current_user_clock_in_list(request):
    if request.method == 'GET':
        # 获取当前用户ID
        user_id = request.GET.get('user_id')
        if not user_id:
            return JsonResponse(tools.ReturnData(code=400, msg='缺少用户ID参数'))
            
        try:
            # 获取当前用户的打卡记录
            clock_ins = ClockIn.objects.filter(user_id=user_id).order_by('-clock_time')
            data = []
            for clock_in in clock_ins:
                clock_in_dict = model_to_dict(clock_in)
                clock_in_dict['clock_time'] = clock_in.clock_time.strftime('%Y-%m-%d %H:%M:%S')
                clock_in_dict['clock_type'] = clock_in.get_clock_type_display()

                # 获取打卡照片
                photos = ClockInPhoto.objects.filter(clock_in=clock_in)
                photos_data = []
                for photo in photos:
                    photo_dict = model_to_dict(photo)
                    photo_dict['photo'] = photo.photo.url
                    photos_data.append(photo_dict)
                clock_in_dict['photos'] = photos_data
                
                data.append(clock_in_dict)
                
            return JsonResponse(tools.ReturnData(code=200, data=data))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取打卡记录失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))


# 获取打卡详情
@csrf_exempt
def get_clock_in_detail(request, clock_in_id):
    if request.method == 'GET':
        try:
            clock_in = ClockIn.objects.get(id=clock_in_id)
            data = model_to_dict(clock_in)
            data['clock_time'] = clock_in.clock_time.strftime('%Y-%m-%d %H:%M:%S')
            data['clock_type'] = clock_in.get_clock_type_display()
            # 获取打卡照片
            photos = ClockInPhoto.objects.filter(clock_in=clock_in)
            photos_data = []
            for photo in photos:
                photo_dict = model_to_dict(photo)
                photo_dict['photo'] = photo.photo.url
                photos_data.append(photo_dict)
            data['photos'] = photos_data
            user = clock_in.user
            user_dict = model_to_dict(user)
            user_dict['avatar'] = user.avatar.url if user.avatar else None
            del user_dict['password']
            data['user'] = user_dict
            return JsonResponse(tools.ReturnData(code=200, data=data))
        except ClockIn.DoesNotExist:
            return JsonResponse(tools.ReturnData(code=400, msg='打卡记录不存在'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))


# 删除打卡
@csrf_exempt
def delete_clock_in(request, clock_in_id):
    if request.method == 'DELETE':
        try:
            clock_in = ClockIn.objects.get(id=clock_in_id)
            clock_in.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除打卡成功'))
        except ClockIn.DoesNotExist:
            return JsonResponse(tools.ReturnData(code=400, msg='打卡记录不存在'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))


# 删除打卡照片
@csrf_exempt
def delete_clock_in_photo(request, photo_id):
    if request.method == 'DELETE':
        try:
            photo = ClockInPhoto.objects.get(id=photo_id)
            photo.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除打卡照片成功'))
        except ClockInPhoto.DoesNotExist:
            return JsonResponse(tools.ReturnData(code=400, msg='打卡照片不存在'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))

